package chapter4.homework;

class Number2 {
    private int num = 1; // 用来记录线程要打印的数字
    private boolean odd = true; // 用来标记是奇数线程打印还是偶数线程打印

    // 打印奇数的方法
    public synchronized void printOddNum() {
        while (num <= 100) {
            if (odd) {
                System.out.println("奇数线程打印: " + num);
                num++;
                odd = false; // 切换到偶数线程
                notifyAll(); // 唤醒其他线程
            }
            try {
                wait(); // 当前线程等待
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    }

    // 打印偶数的方法
    public synchronized void printEvenNum() {
        while (num <= 100) {
            if (!odd) {
                System.out.println("偶数线程打印: " + num);
                num++;
                odd = true; // 切换到奇数线程
                notifyAll(); // 唤醒其他线程
            }
            try {
                wait(); // 当前线程等待
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    }
}

public class Q2文心一言 {
    public static void main(String[] args) {
        Number2 number = new Number2();

        // 创建并启动奇数线程
        Thread oddThread = new Thread(() -> {
            while (true) {
                number.printOddNum();
                try {
                    Thread.sleep(1000); // 每对数字之间间隔1秒
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        });
        oddThread.start();

        // 创建并启动偶数线程
        Thread evenThread = new Thread(() -> {
            while (true) {
                number.printEvenNum();
                try {
                    Thread.sleep(1000); // 每对数字之间间隔1秒
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        });
        evenThread.start();
    }
}
